package com.api.syh56.shengyunhui.service.impl;

import com.api.syh56.shengyunhui.common.BaseUserInfo;
import com.api.syh56.shengyunhui.common.Constants;
import com.api.syh56.shengyunhui.common.UserInfoEnu;
import com.api.syh56.shengyunhui.entity.*;
import com.api.syh56.shengyunhui.entity.vo.WAGParamVO;
import com.api.syh56.shengyunhui.entity.vo.WAGParamVOAndQuote;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.mapper.QuoteMapper;
import com.api.syh56.shengyunhui.mapper.UserMapper;
import com.api.syh56.shengyunhui.mapper.WayBillMapper;
import com.api.syh56.shengyunhui.properties.WechatProperties;
import com.api.syh56.shengyunhui.service.*;
import com.api.syh56.shengyunhui.util.CodeToOidUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.app.AppServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class QuoteServiceImpl extends ServiceImpl<QuoteMapper, Quote> implements QuoteService {

    @Autowired
    private WayBillMapper wayBillMapper;

    @Autowired
    private WayBillService wayBillService;

    @Autowired
    private UserService userService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private QuoteMapper quoteMapper;

    public Page<WAGParamVOAndQuote> quotePageToWAGParamVOAndQuotePage(Page<Quote> quotePage) {
        System.out.println(quotePage.getRecords());
        Page<WAGParamVOAndQuote> wagParamVOAndQuotesPage = new Page<>();
// 复制分页信息
        wagParamVOAndQuotesPage.setCurrent(quotePage.getCurrent());
        wagParamVOAndQuotesPage.setSize(quotePage.getSize());
        wagParamVOAndQuotesPage.setPages(quotePage.getPages());
        wagParamVOAndQuotesPage.setTotal(quotePage.getTotal());
// 转换数据列表方法1（Stream API）
        List<WAGParamVOAndQuote> wagParamVOAndQuoteList = quotePage.getRecords().stream()
                .map(quote -> convertToWAGParamVOAndQuote(quote)) // 使用方法引用进行转换
                .collect(Collectors.toList());

// 转换数据列表方法2
//                List<WAGParamVO> waybilltestList= new ArrayList<>();
//                waybillPage.getRecords().forEach(waybill -> {
//                    WAGParamVO wagParamVO = wayBillService.convertToWAGParamVO(waybill.getId());
//                    waybilltestList.add(wagParamVO);
//                });
// 将转换后的列表设置到新的 Page 对象中
        wagParamVOAndQuotesPage.setRecords(wagParamVOAndQuoteList);
        return wagParamVOAndQuotesPage;
    }

    public WAGParamVOAndQuote convertToWAGParamVOAndQuote(Quote quote){
        Long waybillId = quote.getWaybillId();
        System.out.println("waybillId:"+waybillId);
        Waybill waybill = wayBillMapper.selectById(waybillId);
        WAGParamVO wagParamVO = wayBillService.convertToWAGParamVO(waybillId);
        WAGParamVOAndQuote wagParamVOAndQuote = new WAGParamVOAndQuote();
        wagParamVOAndQuote.setWagParamVO(wagParamVO);
        wagParamVOAndQuote.setQuote(quote);

        //获取报价司机信息
        Long driverId = quote.getDriverId();
        wagParamVOAndQuote.setDriver_user(userService.getById(driverId));
        QueryWrapper<Driver> driverQueryWrapper = new QueryWrapper<>();
        driverQueryWrapper.lambda().eq(Driver::getUid,driverId);
        wagParamVOAndQuote.setDriver(driverService.getOne(driverQueryWrapper));
        return wagParamVOAndQuote;
    }

    @Override
    public Page<WAGParamVOAndQuote> quoteRecentPage(Page page, Short status) {
        Long driverId = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));
        QueryWrapper<Quote> quoteQueryWrapper = new QueryWrapper<>();
        //查看 进行中 的报价
        quoteQueryWrapper.lambda()
                .eq(Quote::getDriverId,driverId)
                .in(Quote::getStatus, Arrays.asList(Constants.QuoteStatus.IN_PROGRESS, Constants.QuoteStatus.UNSELECTED,Constants.QuoteStatus.SHIPPER_RETRACTED))
                .orderByDesc(Quote::getCreationTime);

        Page quotePage = page(page, quoteQueryWrapper);
        Page QWAGpage = quotePageToWAGParamVOAndQuotePage(quotePage);

        return QWAGpage;
    }

    @Async
    @Override
    public void confirmQuote(Quote quote) {
        Long quoteId = quote.getId();
        // 更新选中的报价状态
        quote.setStatus(Constants.QuoteStatus.SELECTED);
        updateById(quote);

        // 更新该订单其他报价的状态
        QueryWrapper<Quote> quoteQueryWrapper = new QueryWrapper<>();
        Long waybillId = quote.getWaybillId();
        quoteQueryWrapper.lambda()
                .eq(Quote::getWaybillId, waybillId)
                .ne(Quote::getId, quoteId); // 添加条件排除当前选中的报价
        List<Quote> quoteList = list(quoteQueryWrapper);
        for (Quote quoteItem : quoteList) {
            quoteItem.setStatus(Constants.QuoteStatus.UNSELECTED);
            updateById(quoteItem); // 更新状态为未选中
        }
    }

    @Override
    public void cancelWaybillAndUpdateQuote(Long waybillId) {
        // 更新该订单其他报价的状态
        QueryWrapper<Quote> quoteQueryWrapper = new QueryWrapper<>();
        quoteQueryWrapper.lambda()
                .eq(Quote::getWaybillId, waybillId);
        List<Quote> quoteList = list(quoteQueryWrapper);
        for (Quote quoteItem : quoteList) {
            quoteItem.setStatus(Constants.QuoteStatus.SHIPPER_RETRACTED);
            updateById(quoteItem); // 更新状态为货主已撤回SHIPPER_RETRACTED
        }
    }

    @Override
    public void getQuo() {
        List<Quote> quotes = quoteMapper.selectList(null);
        for (Quote quote : quotes){
            Long waybillId = quote.getWaybillId();
            Waybill waybill = wayBillService.getById(waybillId);
            if (waybill == null) {
                quoteMapper.deleteById(quote.getId());
            }
        }
    }

    @Override
    public void deleteQuote(Long id) {
        Quote quote = quoteMapper.selectById(id);
        Waybill waybill = wayBillService.getById(quote.getWaybillId());
        if (waybill == null) {
            quoteMapper.deleteById(id);
        }
    }


}
